package uestc.lj.gulishop.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import uestc.lj.common.to.SeckillOrderTO;
import uestc.lj.common.utils.R;
import uestc.lj.common.vo.MemberResponseVO;
import uestc.lj.gulishop.seckill.feign.CouponFeignService;
import uestc.lj.gulishop.seckill.feign.ProduceFeignService;
import uestc.lj.gulishop.seckill.interceptor.LoginUserInterceptor;
import uestc.lj.gulishop.seckill.service.SeckillService;
import uestc.lj.gulishop.seckill.to.SeckillSkuRedisTO;
import uestc.lj.gulishop.seckill.vo.SeckillSessionsWithSkus;
import uestc.lj.gulishop.seckill.vo.SkuInfoVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author:Crazlee
 * @Date:2021/6/23
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProduceFeignService produceFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    /**
     * 处理getCurrentSeckillSkus()的降级限流方案
     *
     * @return
     */
    public List<SeckillSkuRedisTO> blockHandlerGetCurrentSeckillSkus(BlockException exception) {
        log.error("获取最近秒杀活动商品失败！自动触发限流逻辑!!!,{}", exception.getMessage());
        return null;
    }

    /**
     * 返回当前时间可以参与的秒杀商品信息
     *
     * @return
     */
    @Override
    @SentinelResource(value = "getCurrentSeckillSkus", blockHandler = "blockHandlerGetCurrentSeckillSkus")
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        // 1.确定当前时间属于哪个秒杀场次
        long nowTime = System.currentTimeMillis();
        // 使用sentinel自定义限流保护资源
        try (Entry entry = SphU.entry("currentSeckillSkus")) {
            // 2.获取redis中所有场次的key
            Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                // 3.获取场次活动时间
                String[] sessionTime = key.replace(SESSIONS_CACHE_PREFIX, "").split("_");
                long sessionStart = Long.parseLong(sessionTime[0]);
                long sessionEnd = Long.parseLong(sessionTime[1]);
                // 4.判断当前时间是否在活动区间
                if (nowTime >= sessionStart && nowTime <= sessionEnd) {
                    // 5. 获取当前场次需要秒杀的所有商品信息
                    // 5.1获取当前场次id+商品id的集合
                    List<String> values = stringRedisTemplate.opsForList().range(key, 0, -1);
                    // 5.2根据之前的values到商品集合中查找
                    BoundHashOperations<String, String, String> operations =
                            stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    if (values != null) {
                        // 根据key查到sku的信息
                        List<String> skuList = operations.multiGet(values);
                        if (skuList != null) {
                            return skuList.stream().map(item -> {
                                // 转换类型
                                return JSON.parseObject(item.toString(), SeckillSkuRedisTO.class);
                            }).collect(Collectors.toList());
                        }
                    }
                }
            }
        } catch (BlockException exception) {
            log.error("获取最近秒杀活动商品失败！自动触发限流逻辑!!!,{}", exception.getMessage());
        }

        return null;
    }

    /**
     * 根据skuId获取当前商品的秒杀活动信息
     *
     * @param skuId
     * @return
     */
    @Override
    public List<SeckillSkuRedisTO> getSkuSeckillInfo(Long skuId) {
        // 1.找到所有需要参与秒杀商品的key
        BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = operations.keys();

        if (keys != null && keys.size() > 0) {
            List<SeckillSkuRedisTO> seckillSkuRedisTOList = new ArrayList<>();

            // 2.正则匹配出符合当前skuId商品的json字符串
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String skuValue = operations.get(key);
                    // 3.类型转换
                    SeckillSkuRedisTO seckillSkuRedisTO = JSON.parseObject(skuValue, SeckillSkuRedisTO.class);
                    // 4.处理随机码
                    long current = System.currentTimeMillis();
                    if (current >= seckillSkuRedisTO.getStartTime() && current <= seckillSkuRedisTO.getEndTime()) {
                    } else {
                        // 不在秒杀活动时间，处理随机码
                        seckillSkuRedisTO.setRandomCode("不在秒杀活动时间范围内");
                    }
                    seckillSkuRedisTOList.add(seckillSkuRedisTO);
                    return seckillSkuRedisTOList;
                }
            }
        }
        return null;
    }

    /**
     * 执行秒杀逻辑
     *
     * @param killId 秒杀场次+秒杀商品id
     * @param key    秒杀活动的随机码
     * @param num    抢购数量
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        // 获取当前登录用户
        MemberResponseVO memberResponseVO = LoginUserInterceptor.loginUser.get();

        // 1. 获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String seckillSkuValue = operations.get(killId);
        if (!StringUtils.isEmpty(seckillSkuValue)) {
            // 2.类型转换得到秒杀的详细信息
            SeckillSkuRedisTO seckillSkuRedisTO = JSON.parseObject(seckillSkuValue, SeckillSkuRedisTO.class);
            // 3.合法性校验--->校验活动时间
            Long startTime = seckillSkuRedisTO.getStartTime();
            Long endTime = seckillSkuRedisTO.getEndTime();
            long currentTime = System.currentTimeMillis();
            if (currentTime >= startTime && currentTime <= endTime) {
                // 3.合法性校验---->校验随机码和商品id
                String code = seckillSkuRedisTO.getRandomCode();
                String killID = seckillSkuRedisTO.getPromotionSessionId() + "_" + seckillSkuRedisTO.getSkuId();
                if (code.equals(key) && killID.equals(killId)) {
                    // 3.合法性校验---->校验限购数量
                    if (num <= seckillSkuRedisTO.getSeckillLimit()) {
                        // 4.合法性校验---->校验当前用户是否已经购买过（幂等性）
                        // 存入redis---->key：用户id+killId,value：用户购买数量,自动过期
                        String memberBuyKey = memberResponseVO.getId() + "_" + killID;
                        Boolean isBuyed = stringRedisTemplate.opsForValue().setIfAbsent(memberBuyKey, num.toString(),
                                (endTime - startTime), TimeUnit.MILLISECONDS);
                        if (isBuyed) {
                            // 未购买过，执行抢占信号量逻辑
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + killId + "_" + key);

                            boolean buyPower = semaphore.tryAcquire(num);
                            if (buyPower) {
                                // 5.抢占成功，秒杀成功，向MQ消息队列发送消息,返回订单号
                                String orderSn = IdWorker.getTimeId();
                                // 6.创建消息实体类
                                SeckillOrderTO seckillOrderTO = new SeckillOrderTO();
                                // 订单号
                                seckillOrderTO.setOrderSn(orderSn);
                                // 会员Id
                                seckillOrderTO.setMemberId(memberResponseVO.getId());
                                // 购买数量
                                seckillOrderTO.setNum(num);
                                // 活动场次id
                                seckillOrderTO.setPromotionSessionId(seckillSkuRedisTO.getPromotionSessionId());
                                // 商品id
                                seckillOrderTO.setSkuId(seckillSkuRedisTO.getSkuId());
                                // 商品秒杀价格
                                seckillOrderTO.setSeckillPrice(seckillSkuRedisTO.getSeckillPrice());

                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTO);

                                return orderSn;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 上架最近三天的秒杀商品信息
     */
    @Override
    public void uploadSeckillSkuInThreeDays() {
        // 1.扫描数据库查询活动
        R latestThreeDaysSession = couponFeignService.getLatestThreeDaysSession();
        if (latestThreeDaysSession.getCode() == 0) {
            // 2.上架商品
            List<SeckillSessionsWithSkus> seckillSessionsWithSkusList = latestThreeDaysSession.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            // 3.1将活动信息缓存到redis
            saveSessionInfos(seckillSessionsWithSkusList);
            // 3.2将活动的关联商品信息缓存到redis
            saveSessionSkuInfos(seckillSessionsWithSkusList);
        }
    }

    /**
     * 将活动的关联商品信息缓存到redis
     * key:场次id+商品id
     *
     * @param seckillSessionsWithSkusList
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> seckillSessionsWithSkusList) {
        seckillSessionsWithSkusList.stream().forEach(session -> {
            // 1.准备hash操作
            BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

            // 商品随机码
            String code = UUID.randomUUID().toString().replace("-", "");

            session.getSeckillSkuRelationEntities().stream().forEach(seckillSkuVO -> {
                // 接口幂等性
                if (!operations.hasKey(seckillSkuVO.getPromotionSessionId().toString() + "_" + seckillSkuVO.getSkuId().toString())) {
                    SeckillSkuRedisTO seckillSkuRedisTO = new SeckillSkuRedisTO();

                    // 2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVO, seckillSkuRedisTO);

                    // 3.缓存sku基本数据
                    R skuInfo = produceFeignService.skuInfo(seckillSkuVO.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVO skuInfoVO = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                        });
                        seckillSkuRedisTO.setSkuInfo(skuInfoVO);
                    }
                    // 4.活动开始和结束时间
                    seckillSkuRedisTO.setStartTime(session.getStartTime().getTime());
                    seckillSkuRedisTO.setEndTime(session.getEndTime().getTime());
                    // 5.商品的随机码
                    seckillSkuRedisTO.setRandomCode(code);

                    // 将当前秒杀活动实体存入redis缓存
                    String s = JSON.toJSONString(seckillSkuRedisTO);
                    // 防止不同场次的重复商品上架
                    operations.put(seckillSkuVO.getPromotionSessionId().toString() + "_" + seckillSkuVO.getSkuId().toString(),
                            s);
                    // 6.使用库存作为分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE
                            + seckillSkuVO.getPromotionSessionId().toString() + "_" + seckillSkuVO.getSkuId().toString()
                            + "_" + code);
                    semaphore.trySetPermits(seckillSkuVO.getSeckillCount());
                }
            });
        });
    }

    /**
     * 将活动信息缓存到redis
     * key:活动的开始时间和结束时间
     * value:活动的场次id+所涉及的商品id
     *
     * @param seckillSessionsWithSkuses
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> seckillSessionsWithSkuses) {
        if (seckillSessionsWithSkuses != null) {
            seckillSessionsWithSkuses.stream().forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();

                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                // 缓存活动信息
                Boolean hasKey = stringRedisTemplate.hasKey(key);
                // 接口幂等性
                if (!hasKey) {
                    List<String> seckillSkuIds =
                            session.getSeckillSkuRelationEntities()
                                    .stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString())
                                    .collect(Collectors.toList());
                    stringRedisTemplate.opsForList().leftPushAll(key, seckillSkuIds);
                }
            });
        }
    }

}
